<?php
include('./config.php');

/**
 * Function which gets the selectClause elements when 'o' is chosen
 * When 'o' is chosen, 'From' takes all tables
 * This function checks if the selectClause elements need all tables
 * If not, remove the unnecessary table
 * @param array 'type from the result of the function "getSelectElementWhenOChosen($aM)" '
 */
function getSelectTableWhenOChosen($tempSelectElement){
	$tempSelectTable = array('TF','TDate','TStore','TProduct');
	
	foreach($tempSelectTable as $k => $tableName){
		$isDelete = true;
		foreach($tempSelectElement as $tableAndElement){
			$temp = explode('.',$tableAndElement);// only 2 elements
			if($temp[0] == $tableName){$isDelete = false;break;}
		}
		if($isDelete){unset($tempSelectTable[$k]);}
	}
	return $tempSelectTable;
}

/**
 * Function which gets the selectClause elements when 'o' is chosen
 * When 'o' is chosen, classificateur takes all elements
 * This function checks the elements of mesure and remove from 'classficateur elements' 
 * the one which is in mesure 
 * @param hashtable 'type from the result of the function "getElementsFrom('_c')" ' // mesure elements
 * @return array elements of classificateur(ex: array('TF.store','TProduct.category',...))
 */
function getSelectElementWhenOChosen($aM){
	$tempSelectElement = array('TF.date','TF.store','TF.product','TF.quantity','TDate.month','TStore.city','TStore.region','TProduct.category','TProduct.supplier');
	
	// Remove element of mesure which is in $tempSelectElement from $tempSelectElement
	foreach($aM as $elementName => $elementInfo){
		// Priority: TF
		// [0]: when element belongs to one table ; [1]: when it belongs to 2 tables
		// We have to choose TF so that we can remove an element from $tempSelectElement
		$mesureElementtable = (count($elementInfo['tables']) == 1) ? $elementInfo['tables'][0] : $elementInfo['tables'][1];
		foreach($tempSelectElement as $key => $value){
			if( $mesureElementtable.'.'.$elementName == $value){unset($tempSelectElement[$key]);}
		}
		// Note: We don't need to worry if ($tempSelectElement)==0) because for 'mesure' there must be an element so 'select clause' will never be empty
	}
	return $tempSelectElement;
}

/**
 * Function that get the info about restriction values for all elements
 * @param hashtable 'type from the result of the function "getElementsFrom($letter)" '
 * @return hashtable<tableElement,array(restrictionValue1,restrictionValue2)>
 * ex: <TStore.city,array('paris','lille')>
 */
function getTableElementRestrictionValues($h){
	$res = array();
	foreach($h as $elementName => $elementInfo){
		$tableName = $elementInfo['tables'][0];
		$restrictionValues = $elementInfo['restrictionValue'];
		if($restrictionValues != null){
			$restrictionValues = explode(';',$restrictionValues);
			$res[$tableName.'.'.$elementName] = $restrictionValues;
		}
	}
	return $res;
}

/**
 * Function that check the parameter and give the appropriate where clause
 * @param string $tableAndElement (ex: TF.store, TStore.city; (mesure)count(TDate.date) as 'dateCount' )
 * @return string $whereClause (ex: TF.product = TProduct.product AND TF.date = TDate.date) 
 */
function getWhereClause($tableAndElement){
	// This is the processing for mesure elements
	if(strpos($tableAndElement,'(') == true){
		$tableAndElement = getStringBetweenTwoDelimiters($tableAndElement,'(',')') ;
	}

	$whereClause = null;
	$tableElement = explode('.',$tableAndElement);// only 2 elements
	$tableName = $tableElement[0];
	$elementName = $tableElement[1];
	if($tableName != 'TF'){		
		// Find the primary key of this table
		$primaryKey = $GLOBALS[$tableName][0];
		// Jointure between this primary key & TF.attribut (same name as the key)
		$whereClause = 'TF.'.$primaryKey.' = '.$tableName.'.'.$primaryKey;		
	}
	return $whereClause;
}

/**
 * Get the a string between 2 delimiters
 * @param string "blalbal (elementName) blabla"
 * @param string $delimiterStart (ex: '(' )
 * @param string $delimiterStart (ex: ')' or '.' )
 * @return string element between two delimiters
 */
function getStringBetweenTwoDelimiters($s,$delimiterStart,$delimiterEnd){
	$positionStart = strpos($s,$delimiterStart);
	$postionEnd = strpos($s,$delimiterEnd);
	
	return substr($s,$positionStart+1,$postionEnd-$positionStart-1);
}

/**
 * Get the name of element from a string
 * @param string "month - f1 o f"
 * @return string "f1 o f"
 */
function getPath($s){
	$positionStart = strpos($s,'-') + 1;	
	return substr($s,$positionStart,strlen($s)-$positionStart);
}

/**
 * Get the table name and elements that are in the form so that we can group the query
 * @param hashtable 'type from the result of the function "getElementsFrom($letter)" '
 * @param (optional) isPriorityTF true: TF is the main table which is chosen; false: it is the second
 * @return hashtable<tableName,'list of element names which are in the formulaire'> 
 * (ex: <'TStore',array( 'count(store) as 'StoreCount'  ,city' )>,..)
 */
function getTableAndElementName($h,$isPriorityTF = false){
	$res = array();
	foreach($h as $elementName => $elementInfo){
		$tableName = ($isPriorityTF == true && count($elementInfo['tables']) == 2) ? $elementInfo['tables'][1] : $elementInfo['tables'][0];
		if($elementInfo['operator'] != null){
			$s = $elementInfo['operator'].'('.$tableName.'.'.$elementName.')';
			if($elementInfo['outputName'] != null){
				$s .= " as '".$elementInfo['outputName']."'";
			}
			$res[$tableName][] = $s;
		}
		else{$res[$tableName][] = $elementName;}
	}
	return $res;
}

/**
 * Get the elements and their relative values from classificateur|mesure
 * @param string $letter (ie $letter = 'c' for classificateur, 'm' for mesure)
 * @return hashtable<name,h1> 
 * with h1:hashtable<'operator' => sum|avg|count|max|min>
 * 					<'ouput' => outputName>
 * 					<'restrictionType' => '=' | null >
 * 					<'restrictionValue' => 'store 1;store 2...' | null >
 */
function getElementsFrom($letter){
	$res = array();
	foreach($_POST as $var => $val){
		if(substr($var,0,2) == $letter){
			// Get the element name
			$e = substr($var,2,strlen($var) - 2);
			$res[$e] = array();
			$res[$e]['restrictionType'] = (isset($_POST[$e.'RestrictionType'])) ? $_POST[$e.'RestrictionType'] : null ;
			$res[$e]['restrictionValue'] = (isset($_POST[$e.'RestrictionValue'])) ? $_POST[$e.'RestrictionValue'] : null ;
			$res[$e]['operator'] = (isset($_POST[$e.'Operator'])) ? $_POST[$e.'Operator'] : null ;
			$res[$e]['outputName'] = (isset($_POST[$e.'OutputName'])) ? $_POST[$e.'OutputName'] : null ;	
			$res[$e]['tables'] = getTablesOfFromElementName($e);
			$res[$e]['path'] = getPath($_POST[$letter.''.$e]);//substr($s,$positionStart+1,$postionEnd-$positionStart-1);
			$res[$e]['havingOperator'] = (isset($_POST[$e.'HavingOperateur'])) ? $_POST[$e.'HavingOperateur'] : null ;
			$res[$e]['havingValue'] = (isset($_POST[$e.'HavingValue'])) ? $_POST[$e.'HavingValue'] : null ;
		}
	}
	return $res;
}

/**
 * Get tables contanning element name
 * Note: TF will be the last table which is chosen
 * @param string $elementName
 * @return array
 */
function getTablesOfFromElementName($elementName){
	$res = array();
	
	if(in_array($elementName,$GLOBALS['TDate'])){$res[] = 'TDate';}
	if(in_array($elementName,$GLOBALS['TStore'])){$res[] = 'TStore';}
	if(in_array($elementName,$GLOBALS['TProduct'])){$res[] = 'TProduct';}
	if(in_array($elementName,$GLOBALS['TF'])){$res[] = 'TF';}
	
	return $res;
}

function test(){
	print_r($GLOBALS['TDate']);
}
?>
